//
//  OCUnitPlus.m
//  OCUnitPlus
//
//  Created by William Zhao on 13-7-31.
//  Copyright (c) 2013年 William Zhao. All rights reserved.
//

#import "OCUnitPlus.h"
#import <objc/runtime.h>

@implementation SenTestSuitePlus

-(void)performTest:(SenTestRun *) aTestRun
{
    NSMutableArray* testArr = [self valueForKey:@"tests"];
    if([self respondsToSelector:@selector(order)]){
        [testArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            NSArray* orderArr = [self performSelector:@selector(order)];
            NSUInteger index1 = [orderArr indexOfObject:[obj1 description]];
            NSUInteger index2 = [orderArr indexOfObject:[obj2 description]];
            if(index1>index2)
                return NSOrderedDescending;
            else if (index1<index2)
                return NSOrderedAscending;
            else
                return NSOrderedSame;
        }];
    }
    [super performTest:aTestRun];
}

@end

@implementation SenTestProbe (Extension)

+ (SenTestSuite *)specifiedTestSuite {
    static SenTestSuitePlus *specifiedTestSuite = nil;
    if (specifiedTestSuite == nil) {
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        NSString *testScope = [self testScope];
        if ([testScope isEqualToString:SenTestScopeAll]) {
            ASSIGN (specifiedTestSuite, [SenTestSuitePlus defaultTestSuite]);
        }
        else if ([testScope isEqualToString:SenTestScopeSelf]) {
            ASSIGN (specifiedTestSuite, [SenTestSuitePlus testSuiteForBundlePath:[self testedBundlePath]]);
        }
        else if (![testScope isEqualToString:SenTestScopeNone]) {
            ASSIGN (specifiedTestSuite, [SenTestSuitePlus testSuiteForTestCaseWithName:testScope]);
        }
        [pool release];
    }
    return specifiedTestSuite;
}

+ (void)load {
    Method newMethod = nil;
    newMethod = class_getClassMethod([self class], @selector(runTestsOrdered:));
    if (newMethod) {
        class_replaceMethod(objc_getMetaClass(class_getName([self class])),  @selector(runTests:), method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
    }
}

+ (void)runTestsOrdered:(id)ignored {
    BOOL hasFailed  = NO;
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [[NSBundle allFrameworks] makeObjectsPerformSelector:@selector(principalClass)];
    [SenTestObserver class];
    SenTestSuitePlus* suite = (SenTestSuitePlus*)[self specifiedTestSuite];
    hasFailed = ![[suite run] hasSucceeded];
    [pool release];
    exit ((int) hasFailed);
}

@end